package cn.edu.my.jsoup.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import cn.edu.my.jsoup.dao.TradeWriterDao;
import cn.edu.my.jsoup.model.TradeFundFlowDirection;
import cn.edu.my.jsoup.model.base.BaseTrade;
import cn.edu.my.jsoup.model.base.InstanceFactory;

public class TradeWriterDaoImpl implements TradeWriterDao {
	private BaseTrade baseTrade;

	public void writeData(List<BaseTrade> baseTradeList) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("tradeFundFlowDirection");
		EntityManager em = emf.createEntityManager();

		em.getTransaction().begin();

//		if (true == isDuplicate(baseTradeList.get(0).getStockDate())) {
//			return;
//		}
		for (int i = 0; i < baseTradeList.size(); i++) {
			baseTrade = InstanceFactory.getInstance("ChemicalTrade");

			baseTrade.setStockDate(baseTradeList.get(i).getStockDate());
			baseTrade.setStockCode(baseTradeList.get(i).getStockCode());
			baseTrade.setStockName(baseTradeList.get(i).getStockName());
			baseTrade.setPrice(baseTradeList.get(i).getPrice());
			baseTrade.setUpDownRange(baseTradeList.get(i).getUpDownRange());
			baseTrade.setMainForceNetInflowAmount(baseTradeList.get(i).getMainForceNetInflowAmount());
			baseTrade.setMainForceNetInflowPercentage(baseTradeList.get(i).getMainForceNetInflowPercentage());
			baseTrade.setSuperLargeSheetNetInflowAmount(baseTradeList.get(i).getSuperLargeSheetNetInflowAmount());
			baseTrade.setSuperLargeSheetNetInflowPercentage(baseTradeList.get(i).getSuperLargeSheetNetInflowPercentage());
			baseTrade.setLargeSheetNetInflowAmount(baseTradeList.get(i).getLargeSheetNetInflowAmount());
			baseTrade.setLargeSheetNetInflowPercentage(baseTradeList.get(i).getLargeSheetNetInflowPercentage());
			baseTrade.setMiddleSheetNetInflowAmount(baseTradeList.get(i).getMiddleSheetNetInflowAmount());
			baseTrade.setMiddleSheetNetInflowPercentage(baseTradeList.get(i).getMiddleSheetNetInflowPercentage());
			baseTrade.setSmallSheetNetInflowAmount(baseTradeList.get(i).getSmallSheetNetInflowAmount());
			baseTrade.setSmallSheetNetInflowPercentage(baseTradeList.get(i).getSmallSheetNetInflowPercentage());

			em.persist(baseTrade);
		}

		em.getTransaction().commit();
		emf.close();
	}

	private boolean isDuplicate(Date date) {
		Date currentDate = new Date();
		if (currentDate.getYear() == date.getYear()
				&& currentDate.getMonth() == date.getMonth()
				&& currentDate.getDay() == date.getDay()) {
			return true;
		}
		return false;
	}

}
